using System;
using System.Text;
using System.Reflection;
using NHibernate;
using NHibernate.Properties;

namespace Technoera.Common.Nh.CustomPropertyAccessors
{
    public sealed class DateSetter : ISetter
    {
        private System.Type clazz;
        private PropertyInfo property;
        private string propertyName;

        public DateSetter(System.Type clazz, PropertyInfo property, string propertyName)
        {
            this.clazz = clazz;
            this.property = property;
            this.propertyName = propertyName;
        }

        #region ISetter Members

        public void Set(object target, object value)
        {
            try
            {
                if (target is DateTime && value == null)
                {
                    property.SetValue(target, DateTime.MinValue, new object[0]);
                }
                else
                {
                    property.SetValue(target, value, new object[0]);
                }
            }
            catch (Exception e)
            {
                throw new PropertyAccessException(e, "Exception occurred", true, clazz, propertyName);
            }
        }

        public string PropertyName
        {
            get { return property.Name; }
        }

        public PropertyInfo Property
        {
            get { return property; }
        }

        /// <summary>
        /// Gets the <see cref="PropertyInfo"/> for the mapped Property.
        /// </summary>
        /// <value>The <see cref="PropertyInfo"/> for the mapped Property.</value>
        public MethodInfo Method
        {
            get { return property.GetSetMethod(true); }
        }

        #endregion
    }

}
